package com.prawn.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: zhy
 * @Date: 2019/7/11
 * @Description: 后端管理网关过滤器
 */
@Component
public class ManagetFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 过滤器类型
     *  String
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 排序权重，越小排序越高
     * 
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否使用该过滤器
     * 
     */
    @Override
    public boolean shouldFilter() {
        return false;
    }

    /**
     * 过滤器运行:
     *      经过过滤器会过滤掉Header信息，在进入后台管理前直接实现token的校验
     * 
     * @throws  ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("Manager网关过滤器执行...");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //跨域请求中会出现的方，预试探服务器是否能接受数据
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        //后台登录页面不转发
        String url = request.getRequestURL().toString();
        if (url.indexOf("/admin/login") > 0) {
            return null;
        }
        //验证是否有权限
        String header = request.getHeader("Authorization");
        System.out.println(header);
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                if (claims != null) {
                    //如果是后台管理员，则转发鉴权头信息
                    if ("admin".equals(claims.get("roles"))) {
                        requestContext.addZuulRequestHeader("Authorization",header);
                        System.out.println("后台管理验证通过");
                        return null;
                    }
                }
            } catch (Exception e) {
                System.out.println("token校验失败，用户信息已过期...");
                throw new RuntimeException();
            }
        }
        //
        requestContext.setSendZuulResponse(false);//终止运行
        requestContext.setResponseStatusCode(StatusCode.ACCESSERROR);
        requestContext.setResponseBody("没有该权限！");
        requestContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
